package org.example;

import argo.jdom.JdomParser;
import argo.jdom.JsonNode;
import argo.saj.InvalidSyntaxException;

import java.io.IOException;
import java.io.Reader;

import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
import java.util.TreeMap;

public class JSONDepthParser extends FilesParser {
    private static String regexp = ".+\\.json$";

    private HashMap<String, Double> stationDepths;

    public JSONDepthParser(String root) throws IOException, DataFormatException {
        super(root, regexp);
    }

    public static JSONDepthParser parser(String root) throws IOException, DataFormatException {
        return new JSONDepthParser(root);
    }

    public void clear() {
        stationDepths = new HashMap<>();
    }

    protected void parse(Reader reader) throws IOException, DataFormatException {
        try {
            JsonNode array = new JdomParser().parse(reader);

            for (JsonNode object : array.getElements()) {
                String stationName = object.getStringValue("station_name");

                try {
                    Double depth = Double.valueOf(object
                            .getStringValue("depth")
                            .replace(',', '.')
                    );

                    Double currentDepth = stationDepths.get(stationName);
                    if (currentDepth == null || currentDepth > depth) {
                        stationDepths.put(stationName, depth);
                    }
                } catch (NumberFormatException e) {}
            }
        } catch (InvalidSyntaxException e) {
            clear();
            throw new DataFormatException(e.getMessage());
        } finally {
            reader.close();
        }
    }

    public Map<String, Double> getStationDepths() {
        return new TreeMap<>(stationDepths);
    }

    public Double getStationDepth(String stationName) {
        return stationDepths.get(stationName);
    }

    @Override
    public String toString() {
        StringJoiner stringJoiner = new StringJoiner(System.lineSeparator());

        for (Map.Entry<String, Double> entry : getStationDepths().entrySet()) {
            stringJoiner.add(entry.getKey() + "\t" + entry.getValue());
        }

        return stringJoiner.toString();
    }
}
